package org.lds.scheduled.job.worker.starter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lds.scheduled.job.admin.client.AdminClient;
import org.lds.scheduled.job.admin.client.core.model.request.RegisterWorkerRequest;
import org.lds.scheduled.job.common.exception.BusinessException;
import org.lds.scheduled.job.common.model.dto.ResultDTO;
import org.lds.scheduled.job.common.util.IPUtil;
import org.lds.scheduled.job.common.util.JsonUtil;
import org.lds.scheduled.job.common.util.ScheduledUtil;
import org.lds.scheduled.job.worker.common.enums.WorkerErrorEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RegisterWorkerStarter implements ApplicationRunner {
    private final AdminClient adminClient;

    @Value("${server.port}")
    private int port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ScheduledUtil.defaultClosableScheduled(this::execute);
    }

    private void execute() {
        try {
            ResultDTO<Long> resultDTO = adminClient.registerWorker(RegisterWorkerRequest.builder()
                    .appName(adminClient.getAdminClientProperties().getAppName())
                    .ip(IPUtil.getLocalIp())
                    .port(port)
                    .build());
            log.info("注册worker成功 result={}", JsonUtil.toJson(resultDTO));
        } catch (Exception e) {
            log.error("注册worker失败 cause:{}", e.getMessage());
            throw new BusinessException(WorkerErrorEnum.REGISTER_WORKER_FAIL);
        }
    }

}
